package weixinutil

import (
	"fmt"
	"shop/utils/convertutil"
	"shop/utils/httputil"
)

// GetWxMpOpenid 通过微信小程序授权码获取openid 返回示例：{"session_key":"IX9HxVoc7ZhoTWd2LG4i2Q==","openid":"ogbA_44fnEu4aNnnieP0XPr_Is_0"}
func GetWxMpOpenid(mpAppId, mpAppSecret, wxMpCode string) string {
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&grant_type=authorization_code&js_code=%s", mpAppId, mpAppSecret, wxMpCode)
	data := map[string]interface{}{}
	convertutil.ParseJson(httputil.Get(url), &data)
	if openid := data["openid"]; openid != nil {
		return openid.(string)
	}
	return ""
}

// GetWxGzhOpenid 通过微信扫码后获取的公众号授权码获取openid 返回示例：{"access_token":"52_mU_3sWp8wok1eCFMGl9qAKWpyEVOnv1O0V8SfK7RKJbw5XFSYKYxKmU-n8ui_d13pWELvGSD6r7CaqRq-J1VGOL8ZCXhnM8DedZRtFPHGiQ","expires_in":7200,"refresh_token":"52_BA6ciIgZ9LCAQ6oR0TILKFVLTt0Qv722UHaX6T7NAw3xoNyLno1sbl2x0CDOblRCtS_nu3cuL3obojwANlBF7uRK59xuF-7hIxfNrvKwv8w","openid":"oQBQW6jeHfstqlfCMbPDtRmaXj_I","scope":"snsapi_base"}
func GetWxGzhOpenid(gzhAppId, gzhAppSecret, wxGzhCode string) string {
	url := fmt.Sprintf(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&grant_type=authorization_code&code=%s`, gzhAppId, gzhAppSecret, wxGzhCode)
	data := map[string]interface{}{}
	convertutil.ParseJson(httputil.Get(url), &data)
	if openid := data["openid"]; openid != nil {
		return openid.(string)
	}
	return ""
}
